package services

import (
	"awesome-devops/applications/backend/modules/requests"
	"awesome-devops/applications/models"
	"awesome-devops/boot"
	"fmt"
	"gitee.com/jjawesomejj/awesome-util/helper/commonhelper"
	"gitee.com/jjawesomejj/awesome-util/helper/timeHelper"
)

type ServerConfigService struct {
}

func (service *ServerConfigService) List(keyword string, request requests.PageRequest) interface{} {
	serverConfig := models.ServerConfig{}
	query := boot.GetDbConnection().Table(serverConfig.TableName())
	if keyword != "" {
		query = query.Where("ssh_ip like ? or server_name like ?",
			commonhelper.Format("%{}%", keyword),
			commonhelper.Format("%{}%", keyword),
		)
	}
	res, err := serverConfig.Pager(query, request.Page, request.PageSize, nil)
	if err != nil {
		return err
	}
	return res
}

func (service *ServerConfigService) SelectList() interface{} {
	server := models.ServerConfig{}
	query := boot.GetDbConnection().Table(server.TableName())
	var list []map[string]interface{}
	result := query.Table(server.TableName()).Select("server_name,id,ssh_ip as ip").Find(&list)
	if result.Error != nil {
		return result.Error
	}
	return list
}

func (service *ServerConfigService) HandleHook(beforeHook []map[string]interface{}, afterHook []map[string]interface{}) ([]models.RunStep, []models.RunStep) {
	beforeHookUniqueIds := make([]string, 0)
	afterHookUniqueIds := make([]string, 0)
	hooks := make([]models.RunStep, 0)
	for _, item := range beforeHook {
		hook := getHook(item)
		hook.RunStep = 1
		hooks = append(hooks, hook)
		beforeHookUniqueIds = append(beforeHookUniqueIds, item["unique_id"].(string))
	}
	for _, item := range afterHook {
		hook := getHook(item)
		hook.RunStep = 2
		hooks = append(hooks, hook)
		afterHookUniqueIds = append(afterHookUniqueIds, item["unique_id"].(string))
	}
	boot.GetDbConnection().Save(&hooks)
	beforeHooks := make([]models.RunStep, 0)
	afterHooks := make([]models.RunStep, 0)
	for _, item := range hooks {
		if item.RunStep == 1 {
			beforeHooks = append(beforeHooks, item)
		} else {
			afterHooks = append(afterHooks, item)
		}
	}
	return GetHookByUniqueIds(beforeHookUniqueIds), GetHookByUniqueIds(afterHookUniqueIds)
}

func (service *ServerConfigService) HandleFiles(Files []map[string]interface{}) []models.ProcessFiles {
	fileIds := make([]string, 0)
	hooks := make([]models.ProcessFiles, 0)
	for _, item := range Files {
		hook := getFiles(item)
		hooks = append(hooks, hook)
		fileIds = append(fileIds, item["unique_id"].(string))
	}
	res := boot.GetDbConnection().Save(&hooks)
	if res.Error != nil {
		fmt.Println("错误", res.Error)
	}
	return GetFilesByUniqueIds(fileIds)
}
func GetHookByUniqueIds(uniqueIds []string) []models.RunStep {
	var hooks []models.RunStep
	step := models.RunStep{}
	table := step.TableName()
	boot.GetDbConnection().Table(table).Where("unique_id in ? and delete_time=0", uniqueIds).Find(&hooks)
	return hooks
}

func GetFilesByUniqueIds(uniqueIds []string) []models.ProcessFiles {
	var hooks []models.ProcessFiles
	files := models.ProcessFiles{}
	tableName := files.TableName()
	boot.GetDbConnection().Table(tableName).
		Where("unique_id in ? and delete_time=0", uniqueIds).
		Find(&hooks)
	return hooks
}

func getHook(item map[string]interface{}) models.RunStep {
	hook := models.RunStep{}
	if value, ok := item["id"]; ok {
		hook.ID = uint(value.(float64))
		hook.CreateTime = timeHelper.Now()
		hook.UpdateTime = timeHelper.Now()
	} else {
		hook.UpdateTime = timeHelper.Now()
	}
	hook.StepName = item["step_name"].(string)
	hook.RunType = int(item["run_type"].(float64))
	if value, ok := item["docker_image"]; ok {
		hook.DockerImage = value.(string)
	}
	if value, ok := item["step_template"]; ok {
		hook.StepTemplate = value.(string)
	}
	if value, ok := item["template_args"]; ok {
		hook.TemplateArgs = value.(string)
	}
	if value, ok := item["ext_params"]; ok {
		hook.ExtParams = value.(string)
	}
	hook.UniqueId = item["unique_id"].(string)
	return hook
}

func getFiles(item map[string]interface{}) models.ProcessFiles {
	hook := models.ProcessFiles{}
	if value, ok := item["id"]; ok {
		hook.Id = uint(value.(float64))
		hook.UpdateTime = timeHelper.Now()
		hook.CreateTime = timeHelper.Now()
	} else {
		hook.CreateTime = timeHelper.Now()
		hook.UpdateTime = timeHelper.Now()
	}
	hook.Path = item["path"].(string)
	hook.Content = item["content"].(string)
	if value, ok := item["template_args"]; ok {
		hook.TemplateArgs = value.(string)
	} else {
		hook.TemplateArgs = ""
	}

	hook.UniqueId = item["unique_id"].(string)
	return hook
}

func (service *ServerConfigService) CheckServerIsAlive(serverId float64) error {
	model := models.ServerConfig{}
	err := model.RowByID(int(serverId), &model)
	if err != nil {
		return err
	}
	ssh := model.GetSshDriver(func() (time int, echoWords string, callBack func()) {
		return 2, "服务器连接失败", func() {

		}
	})
	_, err = ssh.RunShell("pwd")
	if err != nil {
		return err
	}
	return nil
}
